import { apiRoot } from 'utils/config';
import { post } from 'utils/request';
import { saveToken, saveUser, autoRedirect } from 'utils';

const $myForm = $('#myForm');

$myForm.find('#username').attr('data-remote', apiRoot + 'user/avail_name');

$myForm.validator().on('submit', function (e) {
  if (e.isDefaultPrevented()) {
    console.log('表单验证不通过');
  } else {
    e.preventDefault();
    let post_data = {
      username: this.username.value,
      email: this.email.value,
      password_1: this.password_1.value,
      password_2: this.password_2.value,
    };
    post('user/users', post_data).done(d => {
      let remember = this.remember.checked;
      saveToken(d.token, remember);
      saveUser(d.user, remember);
      this.reset();
      alert('注册并登录成功');
      autoRedirect();
    });
  }
});
